<!DOCTYPE html>




<html class="theme-next pisces" lang="zh-Hans">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







  

<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.6.2/css/font-awesome.min.css" rel="stylesheet" type="text/css" />

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-james.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-james.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Spring,Spring MVC," />





  <link rel="alternate" href="/atom.xml" title="郑保乐的博客" type="application/atom+xml" />






<meta name="description" content="Spring MVC 是什么Spring Web MVC （Spring MVC) 是一套以 Servlet API 为基础平台的优雅的 Web 框架，一直是 Spring Framework 中重要的一个组成部分。 正式名称 “Spring Web MVC” 来自其源模块 spring-webmvc 的名称，但它通常被称为“Spring MVC”。 与 Spring Web MVC 并行，Spr">
<meta name="keywords" content="Spring,Spring MVC">
<meta property="og:type" content="article">
<meta property="og:title" content="SpringMVC 解析之 DispatcherServlet">
<meta property="og:url" content="https://james.letec.top/2018/03/29/SpringMVC 解析之 DispatcherServlet/index.html">
<meta property="og:site_name" content="郑保乐的博客">
<meta property="og:description" content="Spring MVC 是什么Spring Web MVC （Spring MVC) 是一套以 Servlet API 为基础平台的优雅的 Web 框架，一直是 Spring Framework 中重要的一个组成部分。 正式名称 “Spring Web MVC” 来自其源模块 spring-webmvc 的名称，但它通常被称为“Spring MVC”。 与 Spring Web MVC 并行，Spr">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="https://docs.spring.io/spring/docs/current/spring-framework-reference/images/mvc-context-hierarchy.png">
<meta property="og:updated_time" content="2018-03-29T14:21:39.566Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="SpringMVC 解析之 DispatcherServlet">
<meta name="twitter:description" content="Spring MVC 是什么Spring Web MVC （Spring MVC) 是一套以 Servlet API 为基础平台的优雅的 Web 框架，一直是 Spring Framework 中重要的一个组成部分。 正式名称 “Spring Web MVC” 来自其源模块 spring-webmvc 的名称，但它通常被称为“Spring MVC”。 与 Spring Web MVC 并行，Spr">
<meta name="twitter:image" content="https://docs.spring.io/spring/docs/current/spring-framework-reference/images/mvc-context-hierarchy.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":false,"async":true,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: 'DQH9NUSGTQ',
      apiKey: 'dd999b30a63c88fb422dc71142c6b7bc',
      indexName: 'jamesblog_hexo',
      hits: {"per_page":10},
      labels: {"input_placeholder":"搜索文章标题或内容","hits_empty":"没有在这个星球上找到: ${query}","hits_stats":"共找到 ${hits} 条结果，用时： ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="https://james.letec.top/2018/03/29/SpringMVC 解析之 DispatcherServlet/"/>





  <title>SpringMVC 解析之 DispatcherServlet | 郑保乐的博客</title>
  





  <script type="text/javascript">
    var _hmt = _hmt || [];
    (function() {
      var hm = document.createElement("script");
      hm.src = "https://hm.baidu.com/hm.js?8c29d46a5fdb9bba0c5b918524bba2c0";
      var s = document.getElementsByTagName("script")[0];
      s.parentNode.insertBefore(hm, s);
    })();
  </script>




</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">郑保乐的博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <h1 class="site-subtitle" itemprop="description">James' Blog</h1>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-about">
          <a href="/about/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-user"></i> <br />
            
            关于
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br />
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br />
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br />
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  
  <div class="algolia-popup popup search-popup">
    <div class="algolia-search">
      <div class="algolia-search-input-icon">
        <i class="fa fa-search"></i>
      </div>
      <div class="algolia-search-input" id="algolia-search-input"></div>
    </div>

    <div class="algolia-results">
      <div id="algolia-stats"></div>
      <div id="algolia-hits"></div>
      <div id="algolia-pagination" class="algolia-pagination"></div>
    </div>

    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
  </div>




    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="https://james.letec.top/2018/03/29/SpringMVC 解析之 DispatcherServlet/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="郑保乐">
      <meta itemprop="description" content="优秀的判断力来自经验，<br>但经验来自错误的判断。">
      <meta itemprop="image" content="/images/avatar.jpg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郑保乐的博客">
    </span>

    
      <header class="post-header">

        
        
          <h2 class="post-title" itemprop="name headline">SpringMVC 解析之 DispatcherServlet</h2>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2018-03-29T20:31:22+08:00">
                2018-03-29
              </time>
            

            

            
          </span>

          
            <span class="post-category" >
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/后端/" itemprop="url" rel="index">
                    <span itemprop="name">后端</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
              <span class="post-meta-divider">|</span>
              <span class="post-meta-item-icon">
                <i class="fa fa-comment-o"></i>
              </span>
              
                <a href="/2018/03/29/SpringMVC 解析之 DispatcherServlet/#SOHUCS" itemprop="discussionUrl">
                  <span id="changyan_count_unit" class="post-comments-count hc-comment-count" data-xid="2018/03/29/SpringMVC 解析之 DispatcherServlet/" itemprop="commentsCount"></span>
                </a>
              
            
          

          
          
             <span id="/2018/03/29/SpringMVC 解析之 DispatcherServlet/" class="leancloud_visitors" data-flag-title="SpringMVC 解析之 DispatcherServlet">
               <span class="post-meta-divider">|</span>
               <span class="post-meta-item-icon">
                 <i class="fa fa-eye"></i>
               </span>
               
                 <span class="post-meta-item-text">阅读次数&#58;</span>
               
                 <span class="leancloud-visitors-count"></span>
             </span>
          

          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  6,107 字
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  24 分钟
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h1 id="Spring-MVC-是什么"><a href="#Spring-MVC-是什么" class="headerlink" title="Spring MVC 是什么"></a>Spring MVC 是什么</h1><p>Spring Web MVC （Spring MVC) 是一套以 Servlet API 为基础平台的优雅的 Web 框架，一直是 Spring Framework 中重要的一个组成部分。 正式名称 “Spring Web MVC” 来自其源模块 spring-webmvc 的名称，但它通常被称为“Spring MVC”。</p>
<p>与 Spring Web MVC 并行，Spring Framework 5.0 引入了一个 Reactive stack —— Web框架，其名称 Spring WebFlux 也基于它的源模块 spring-webflux。<br><a id="more"></a></p>
<h1 id="DispatcherServlet"><a href="#DispatcherServlet" class="headerlink" title="DispatcherServlet"></a>DispatcherServlet</h1><p>与许多其他 Web 框架一样，Spring MVC 同样围绕前端页面的控制器模式 (Controller) 进行设计，其中最为核心的 Servlet —— DispatcherServlet 为来自客户端的请求处理提供通用的方法，而实际的工作交由可自定义配置的组件来执行。 这种模型使用方式非常灵活，可以满足多样化的项目需求。</p>
<p>和任何普通的 Servlet 一样，DispatcherServlet 需要根据 Servlet 规范使用 Java 代码配置或在 web.xml 文件中声明请求和 Servlet 的映射关系。 DispatcherServlet 通过读取 Spring 的配置来发现它在请求映射，视图解析，异常处理等方面所依赖的组件。</p>
<p>以下是注册和初始化 DispatcherServlet 的 Java 代码配置示例。 该类将被 Servlet 容器自动检测到：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyWebApplicationInitializer</span> <span class="keyword">implements</span> <span class="title">WebApplicationInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onStartup</span><span class="params">(ServletContext servletCxt)</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 加载 Spring Web Application 的配置</span></span><br><span class="line">        AnnotationConfigWebApplicationContext ac = <span class="keyword">new</span> AnnotationConfigWebApplicationContext();</span><br><span class="line">        ac.register(AppConfig.class);</span><br><span class="line">        ac.refresh();</span><br><span class="line"></span><br><span class="line">        <span class="comment">// 创建并注册 DispatcherServlet</span></span><br><span class="line">        DispatcherServlet servlet = <span class="keyword">new</span> DispatcherServlet(ac);</span><br><span class="line">        ServletRegistration.Dynamic registration = servletCxt.addServlet(<span class="string">"app"</span>, servlet);</span><br><span class="line">        registration.setLoadOnStartup(<span class="number">1</span>);</span><br><span class="line">        registration.addMapping(<span class="string">"/app/*"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>以下是在 web.xml 中注册和初始化 DispatcherServlet 的方法：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">web-app</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">listener-class</span>&gt;</span>org.springframework.web.context.ContextLoaderListener<span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">context-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- Spring 上下文的配置 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>/WEB-INF/app-context.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">context-param</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>app<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.springframework.web.servlet.DispatcherServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span><span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">load-on-startup</span>&gt;</span>1<span class="tag">&lt;/<span class="name">load-on-startup</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>app<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- "/*" 表示将所有请求交由 DispatcherServlet 处理 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="1-应用上下文的层次结构"><a href="#1-应用上下文的层次结构" class="headerlink" title="1. 应用上下文的层次结构"></a>1. 应用上下文的层次结构</h1><p>DispatcherServlet 依赖于一个 WebApplicationContext（对普通 ApplicationContext 的功能扩展）来实现自己的配置。 WebApplicationContext 中包含了一个指向它所关联的 ServletContext 和 Servlet 的链接。 它同时还绑定到 Servlet 上下文中，以便应用程序可以使用 RequestContextUtils 中的静态方法在 WebApplicationContext 进行查找，来判断是否需要调用 DispatcherServlet 中的方法。</p>
<p>对于只有一个 WebApplicationContext 应用程序来说，这已经可以满足使用了。 同时也可以使用具有层次结构的上下文，其中有一个根上下文（或者叫基上下文） 被多个 DispatcherServlet（或其他普通 Servlet）实例所共享，每个实例都有属于自己的子上下文配置。</p>
<p>根上下文通常包含被多个 Servlet 实例共享的公共 bean，例如数据仓库和业务。 这些 bean 被继承下来使用，还可以在特定的 Servlet 的子上下文中重写（即重新声明一个 bean 的配置），子上下文中拥有该 Servlet 所独有的局部 bean 实例：</p>
<p><img src="https://docs.spring.io/spring/docs/current/spring-framework-reference/images/mvc-context-hierarchy.png" alt=""></p>
<p>以下是使用 WebApplicationContext 层次结构的示例配置：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyWebAppInitializer</span> <span class="keyword">extends</span> <span class="title">AbstractAnnotationConfigDispatcherServletInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Class&lt;?&gt;[] getRootConfigClasses() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Class&lt;?&gt;[] &#123; RootConfig.class &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Class&lt;?&gt;[] getServletConfigClasses() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Class&lt;?&gt;[] &#123; App1Config.class &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> String[] getServletMappings() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> String[] &#123; <span class="string">"/app1/*"</span> &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 web.xml 中的配置</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">web-app</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">listener</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">listener-class</span>&gt;</span>org.springframework.web.context.ContextLoaderListener<span class="tag">&lt;/<span class="name">listener-class</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">listener</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">context-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">        <span class="comment">&lt;!-- 根上下文的配置 --&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>/WEB-INF/root-context.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">context-param</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>app1<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-class</span>&gt;</span>org.springframework.web.servlet.DispatcherServlet<span class="tag">&lt;/<span class="name">servlet-class</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">init-param</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-name</span>&gt;</span>contextConfigLocation<span class="tag">&lt;/<span class="name">param-name</span>&gt;</span></span><br><span class="line">            <span class="comment">&lt;!-- app1 专属的的子上下文 --&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">param-value</span>&gt;</span>/WEB-INF/app1-context.xml<span class="tag">&lt;/<span class="name">param-value</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">init-param</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">load-on-startup</span>&gt;</span>1<span class="tag">&lt;/<span class="name">load-on-startup</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="tag">&lt;<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">servlet-name</span>&gt;</span>app1<span class="tag">&lt;/<span class="name">servlet-name</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">url-pattern</span>&gt;</span>/app1/*<span class="tag">&lt;/<span class="name">url-pattern</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">servlet-mapping</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">web-app</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="2-带有特殊功能的-Bean"><a href="#2-带有特殊功能的-Bean" class="headerlink" title="2. 带有特殊功能的 Bean"></a>2. 带有特殊功能的 Bean</h1><p>DispatcherServlet 依靠这些特殊的 bean 来处理请求并返回响应。 这些特殊的 bean 是指实现 WebFlux 框架协议的，同样由 Spring 管理的对象。 这些对象都含有一套默认的配置，但也可以自定义各种属性，从而进行灵活扩展或功能改写。</p>
<table>
<thead>
<tr>
<th>bean 类名</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td> HandlerMapping</td>
<td>将请求映射到处理程序以及用于预处理和后续处理的一系列拦截器。 这种映射有着一套标准，具体的功能因 HandlerMapping 实现而异。            HandlerMapping 的两个最主要实现是 RequestMappingHandlerMapping 和 SimpleUrlHandlerMapping ,前者支持 @RequestMapping 注释方法，它为请求的处理进行 URI 映射的注册。</td>
</tr>
<tr>
<td> HandlerAdapter</td>
<td>协助 DispatcherServlet 调用匹配请求映射的处理程序，且不需要关心如何调用处理程序以及处理程序的任何细节。 例如，调用带注释的控制器中的方法需要先对 @RequestMapping 等注释进行解析。 HandlerAdapter 的主要功能是屏蔽 DispatcherServlet 的实现细节。</td>
</tr>
<tr>
<td> HandlerExceptionResolver</td>
<td>包含各种异常的解决方法，可以将不同的异常映射到响应的处理程序或页面等。</td>
</tr>
<tr>
<td> ViewResolver</td>
<td>将处理程序中的方法返回值（字符串）的逻辑视图名称解析为实际视图，来将响应返回给客户端。</td>
</tr>
<tr>
<td> LocaleResolver, LocaleContextResolver</td>
<td>识别客户端的当前区域设置以估测大概的时区，从而能够返回响应地区的国际化视图。</td>
</tr>
<tr>
<td> ThemeResolver</td>
<td>解析当前 Web 应用程序可用的主题，例如提供个性化布局。</td>
</tr>
<tr>
<td> MultipartResolver</td>
<td>在相应的解析库的辅助下，对 multi-part 请求（比如浏览器的表单文件上传）进行解析。</td>
</tr>
<tr>
<td> FlashMapManager</td>
<td>存储和检索可将参数从一个请求传递到另一个请求的“输入”和“输出”的 FlashMap，通常通过重定向来实现。</td>
</tr>
</tbody>
</table>
<h1 id="3-Web-MVC-的配置"><a href="#3-Web-MVC-的配置" class="headerlink" title="3. Web MVC 的配置"></a>3. Web MVC 的配置</h1><p>应用程序可以单独声明上文中“带有特殊功能的 Bean”中列出的基础版的 bean。 DispatcherServlet 扫描这些 bean 所属的 WebApplicationContext。 如果没有匹配的 bean 类型，它将返回 DispatcherServlet.properties 中的默认类型。</p>
<p>在大多数情况下，MVC 默认配置是最好的实现。 它采用 Java 代码或 XML 文件来配置所需的 bean，同时提供更高级别的配置回调 API 用于改写默认配置。</p>
<h1 id="4-Servlet-的配置"><a href="#4-Servlet-的配置" class="headerlink" title="4.  Servlet 的配置"></a>4.  Servlet 的配置</h1><p>在 Servlet 3.0 以上的版本中，可以用 Java代码或与 web.xml 文件相结合来配置 Servlet 容器。 以下是用 Java 代码注册 DispatcherServlet 的示例：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> org.springframework.web.WebApplicationInitializer;</span><br><span class="line"></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyWebApplicationInitializer</span> <span class="keyword">implements</span> <span class="title">WebApplicationInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">onStartup</span><span class="params">(ServletContext container)</span> </span>&#123;</span><br><span class="line">        XmlWebApplicationContext appContext = <span class="keyword">new</span> XmlWebApplicationContext();</span><br><span class="line">        appContext.setConfigLocation(<span class="string">"/WEB-INF/spring/dispatcher-config.xml"</span>);</span><br><span class="line"></span><br><span class="line">        ServletRegistration.Dynamic registration = container.addServlet(<span class="string">"dispatcher"</span>, <span class="keyword">new</span> DispatcherServlet(appContext));</span><br><span class="line">        registration.setLoadOnStartup(<span class="number">1</span>);</span><br><span class="line">        registration.addMapping(<span class="string">"/"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>WebApplicationInitializer 是 Spring MVC 提供的一个接口，其所有实现类都可以被扫描到，并自动用于初始化任何 Servlet 3 容器。 AbstractDispatcherServletInitializer （WebApplicationInitializer 的一个抽象父类）的实现类可以通过覆盖方法来配置 Servlet 请求映射、DispatcherServlet 配置文件的目录，这样很简单的就实现了 DispatcherServlet 的配置。</p>
<p>如果通过 Java 代码来配置 Spring 的话，需要这样做：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyWebAppInitializer</span> <span class="keyword">extends</span> <span class="title">AbstractAnnotationConfigDispatcherServletInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Class&lt;?&gt;[] getRootConfigClasses() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Class&lt;?&gt;[] getServletConfigClasses() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Class&lt;?&gt;[] &#123; MyWebConfig.class &#125;;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> String[] getServletMappings() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> String[] &#123; <span class="string">"/"</span> &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>如果用 xml 文件来配置 Spring，则只需定义一个 AbstractDispatcherServletInitializer 实现类即可：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyWebAppInitializer</span> <span class="keyword">extends</span> <span class="title">AbstractDispatcherServletInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> WebApplicationContext <span class="title">createRootApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">null</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">protected</span> WebApplicationContext <span class="title">createServletApplicationContext</span><span class="params">()</span> </span>&#123;</span><br><span class="line">        XmlWebApplicationContext cxt = <span class="keyword">new</span> XmlWebApplicationContext();</span><br><span class="line">        cxt.setConfigLocation(<span class="string">"/WEB-INF/spring/dispatcher-config.xml"</span>);</span><br><span class="line">        <span class="keyword">return</span> cxt;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> String[] getServletMappings() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> String[] &#123; <span class="string">"/"</span> &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>AbstractDispatcherServletInitializer 还可以轻松添加 Filter 并自动映射到 DispatcherServlet 中:</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">MyWebAppInitializer</span> <span class="keyword">extends</span> <span class="title">AbstractDispatcherServletInitializer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="comment">// ...</span></span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="keyword">protected</span> Filter[] getServletFilters() &#123;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">new</span> Filter[] &#123;</span><br><span class="line">            <span class="keyword">new</span> HiddenHttpMethodFilter(), <span class="keyword">new</span> CharacterEncodingFilter() &#125;;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>不同的 Filter 都会以不同的名称注册，同时映射到 DispatcherServlet 中。</p>
<p>The isAsyncSupported protected method of AbstractDispatcherServletInitializer provides a single place to enable async support on the DispatcherServlet and all filters mapped to it. By default this flag is set to true.</p>
<p>AbstractDispatcherServletInitializer 中的 isAsyncSupported() 方法可以设置各个 Filter 是否开启异步支持。</p>
<p>如果还想更加细化自定义配置，可以通过重写 createDispatcherServlet() 方法来实现。</p>
<h1 id="5-处理请求"><a href="#5-处理请求" class="headerlink" title="5. 处理请求"></a>5. 处理请求</h1><p>DispatcherServlet 处理请求的规则：</p>
<ul>
<li>在请求中查找并绑定 WebApplicationContext，它可以作为参数被控制器中的方法使用。 默认绑定到 DispatcherServlet.WEB_APPLICATION_CONTEXT_ATTRIBUTE 对应的值。</li>
<li>区域解析器 (LocaleResolver) 也绑定到请求上，它可以在请求解析、呈现视图、准备数据等过程中将信息解析为当前的区域环境。如果无需解析这些信息，可以不用管它。</li>
<li>主题解析器用来决定使用哪个主题。 如果你不使用主题，可以忽略掉它。</li>
<li>如果在应用中声明了 multipart file resolver，则会对请求进行 multipart 检查；如果发现了 multiparts，请求会被包装成 MultipartHttpServlet 来进行处理。</li>
<li>如果返回模型，则会解析并返回视图。 如果没有返回模型（由于其他处理程序拦截了请求，可能出于安全原因），则不会返回视图，因为可能已经有响应返回给客户端了。</li>
</ul>
<p>WebApplicationContext 中声明的 HandlerExceptionResolver bean 可以解析请求处理时抛出的异常。 可以给异常解析器进行特定的配置来解决特定的异常。</p>
<p>DispatcherServlet 还支持返回最后修改日期。 DispatcherServlet 扫描注册的映射关系并，判断找到的处理程序是否实现了 LastModified 接口。 如果实现了，则将 LastModified 接口的 long getLastModified（request）方法的返回值返回给客户端。</p>
<p>在 web.xml 中，可以通过配置 Servlet 的初始化参数（init-param）来自定义一个 DispatcherServlet 的实例。</p>
<p><em>DispatcherServlet 的初始化参数</em></p>
<table>
<thead>
<tr>
<th>参数</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td> contextClass</td>
<td>WebApplicationContext 的实现类，初始化 Servlet 的上下文，默认为 XmlWebApplicationContext</td>
</tr>
<tr>
<td> contextConfigLocation</td>
<td>作为参数传递给在 contextClass 中指定上下文实例，用于标识上下文的位置，接受多个字符串（以逗号分隔），如果同一个 bean 的配置在多个上下文中出现，则以最后一个为准。</td>
</tr>
<tr>
<td> namespace</td>
<td>WebApplicationContext 的命名空间，默认为 <servlet-name> 元素中的值加上“servlet”。比如，<servlet-name>app</servlet-name>，那么，命名空间为 appServlet。</servlet-name></td>
</tr>
</tbody>
</table>
<h1 id="6-拦截器"><a href="#6-拦截器" class="headerlink" title="6. 拦截器"></a>6. 拦截器</h1><p>所有 HandlerMapping 的实现类都支持使用拦截器，特别是将某些功能只应用到特定的请求上时（比如判断权限），拦截器就非常有用。 拦截器必须实现 org.springframework.web.servlet 包中的 HandlerInterceptor，它提供了三个方法，供不同时刻来调用：</p>
<ul>
<li>preHandle(..)：在请求处理前执行…</li>
<li>postHandle(..)：在请求处理后执行…</li>
<li>afterCompletion(..)：在请求处理完全结束后执行…</li>
</ul>
<p>preHandle(..) 方法返回布尔值，可以通过这一点选择来切断或继续请求的处理链。当返回 true 的时候，处理器链会继续执行；返回 false 的时候， DispatcherServlet 就会认为拦截器已经处理了请求或返回了视图，并不会继续被处理链中的其他处理器或拦截器所处理。</p>
<p>请注意，postHandle(..) 对使用 @ResponseBody 和 ResponseEntity 方法的用处不大，在 HandlerAdapter 中， postHandle(..) 调用之前就已经提交响应了。 所以这时再修改响应什么用也没有了。 这种情况下，可以实现 ResponseBodyAdvice，并将其声明为 Controller Advice bean （在 Controller 类上添加 @ControllerAdvice 注解）或直接在 RequestMappingHandlerAdapter 中进行配置。</p>
<h1 id="7-异常处理"><a href="#7-异常处理" class="headerlink" title="7. 异常处理"></a>7. 异常处理</h1><p>在映射或调用请求处理程序 （例如带有 @Controller 注解的控制器） 处理请求时，如果抛出了异常，则 DispatcherServlet 调用 HandlerExceptionResolver bean 来处理异常，然后将错误页面或错误状态码等信息返回个客户端。</p>
<p>下面列出 HandlerExceptionResolver 的几个实现类：</p>
<p><em>HandlerExceptionResolver 实现类</em></p>
<table>
<thead>
<tr>
<th>类名</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td> SimpleMappingExceptionResolver</td>
<td>将异常类型映射到异常页面的视图名，可以很容易实现错误页面的返回</td>
</tr>
<tr>
<td> DefaultHandlerExceptionResolver</td>
<td>处理由 Spring MVC 抛出的异常，可以直接映射到不同的 HTTP 状态码</td>
</tr>
<tr>
<td> ResponseStatusExceptionResolver</td>
<td>处理带有 @ResponseStatus 注解的异常，并将其映射到 HTTP 状态码</td>
</tr>
<tr>
<td> ExceptionHandlerExceptionResolver</td>
<td>通过调用控制器（带有 @Controller 注解或 @ControllerAdvice 注解）中的带有 @ExceptionHandler 注解的方法，来处理异常</td>
</tr>
</tbody>
</table>
<p>如果需要同时映射多个异常类型，需要设置不同异常的权重 （order 属性），权重越高，处理时机越晚。</p>
<h2 id="处理方式"><a href="#处理方式" class="headerlink" title="处理方式"></a>处理方式</h2><p>HandlerExceptionResolver 中可以返回：</p>
<ul>
<li>ModelAndView： 指向视图名</li>
<li>不带属性的 ModelAndView： 如果已经通过权重更低的方法处理过异常了</li>
<li>null： 这个异常无法被当前异常处理器识别，需要丢给接下来的处理器，如果所有处理器都不能处理这个异常，异常会传到 Servlet 容器中，由容器来处理</li>
<li>自定义异常处理请求也非常简单，比如，在 xml 中配置一个 HandlerExceptionResolver 的 bean， Spring MVC 会自动使用内部的默认异常处理器来处理 Spring MVC 抛出的异常（带有 @ResponseStatus 注解的异常或带有 @ExceptionHandler 注解的方法），可以修改这些默认配置或干脆直接重写新的配置。</li>
</ul>
<h2 id="Servlet-容器中定义的错误页面-error-page"><a href="#Servlet-容器中定义的错误页面-error-page" class="headerlink" title="Servlet 容器中定义的错误页面 (error-page)"></a>Servlet 容器中定义的错误页面 (error-page)</h2><p>如果抛出的异常没能被任何 HandlerExceptionResolver 处理，就会传到 Servlet 容器中。如果将 HTTP 响应码设置为 4xx 或 5xx， Servlet 容器会直接返回默认的错误页面。可以在 web.xml 中配置自定义的错误页面：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">error-page</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">location</span>&gt;</span>/error<span class="tag">&lt;/<span class="name">location</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">error-page</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>此时，如果想要对异常处理进一步自定义，可以这样做：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@RestController</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">ErrorController</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@RequestMapping</span>(path = <span class="string">"/error"</span>)</span><br><span class="line">    <span class="function"><span class="keyword">public</span> Map&lt;String, Object&gt; <span class="title">handle</span><span class="params">(HttpServletRequest request)</span> </span>&#123;</span><br><span class="line">        Map&lt;String, Object&gt; map = <span class="keyword">new</span> HashMap&lt;String, Object&gt;();</span><br><span class="line">        map.put(<span class="string">"status"</span>, request.getAttribute(<span class="string">"javax.servlet.error.status_code"</span>));</span><br><span class="line">        map.put(<span class="string">"reason"</span>, request.getAttribute(<span class="string">"javax.servlet.error.message"</span>));</span><br><span class="line">        <span class="keyword">return</span> map;</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>这样就能再次将 /error 请求交给 DispatcherServlet 来处理，这种方式解决了使用 RestController 返回 JSON，而不是返回视图的情况。</p>
<h1 id="8-视图名解析"><a href="#8-视图名解析" class="headerlink" title="8. 视图名解析"></a>8. 视图名解析</h1><p>Spring MVC 定义了 View 和 ViewResolver 这两个接口，View 负责返回视图前的数据准备， ViewResolver 则负责将逻辑视图名映射到实际视图。 屏蔽了具体的视图实现细节。</p>
<p><em>ViewResolver 的几个实现类</em><br>类名  |  功能<br>–|–<br> AbstractCachingViewResolver |  AbstractCachingViewResolver 的实现类会将解析过的视图缓存，缓存可以提升特定视图技术的性能。可以通过设置 cache 属性的值为 false 来将缓存功能关闭。如果想在运行时刷新视图缓存，可以调用 removeFromCache(String viewName, Locale loc) 方法将已缓存内容移除。<br> XmlViewResolver |  可以使用 Spring bean DTD 定义，在 xml 中对其配置。默认的配置文件为 /WEB-INF/views.xml<br> ResourceBundleViewResolver |  通过解析定义的 ResourceBundle bean，将 viewname 解析为视图名，url 解析为视图路径<br> UrlBasedViewResolver |  可以直接将 url 映射到返回值中，无需再进行额外的映射配置，适用于视图结构清晰，可以直接对应匹配的情况<br> InternalResourceViewResolver |  UrlBasedViewResolver 的子类，可以解析 InternalResourceView （比如 Servlet 或 JSP) 以及其子类，比如 JstlView 或 TilesView。可以通过 setViewClass(..) 方法来指定要解析的具体视图类型<br> FreeMarkerViewResolver |  UrlBasedViewResolver 的子类，可以解析 FreeMarkerView 以及自定义的子类<br> ContentNegotiatingViewResolver |  通过请求的 url 或请求头信息来解析视图</p>
<h2 id="处理方式-1"><a href="#处理方式-1" class="headerlink" title="处理方式"></a>处理方式</h2><p>和上面提到的异常解析器一样，通过配置 bean 来解析视图，同样可以指定不同解析器的权重，权重越高，调用时机越晚。</p>
<p>ViewResolver 可以通过返回 null 来表示视图无法解析，如果是 JSP 或 InternalResourceViewResolver，可以判断 JSP 是否存在的唯一方法就是通过执行 RequestDispatcher 的请求调度方法。 因此必须将 InternalResourceViewResolver 的权重配置为所有视图解析器中最高的。</p>
<p>如果返回视图的执行过程不需要处理任何的业务逻辑，可以使用视图控制器来实现：</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Configuration</span></span><br><span class="line"><span class="meta">@EnableWebMvc</span></span><br><span class="line"><span class="keyword">public</span> <span class="class"><span class="keyword">class</span> <span class="title">WebConfig</span> <span class="keyword">implements</span> <span class="title">WebMvcConfigurer</span> </span>&#123;</span><br><span class="line"></span><br><span class="line">    <span class="meta">@Override</span></span><br><span class="line">    <span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">addViewControllers</span><span class="params">(ViewControllerRegistry registry)</span> </span>&#123;</span><br><span class="line">        <span class="comment">// 将 url 为 "/" 的请求映射到名为 home 的视图上</span></span><br><span class="line">        registry.addViewController(<span class="string">"/"</span>).setViewName(<span class="string">"index"</span>);</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<p>在 xml 中这样写：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">mvc:view-controller</span> <span class="attr">path</span>=<span class="string">"/"</span> <span class="attr">view-name</span>=<span class="string">"index"</span>/&gt;</span></span><br></pre></td></tr></table></figure>
<h2 id="重定向"><a href="#重定向" class="headerlink" title="重定向"></a>重定向</h2><p>如果返回的视图名以 “redirect:” 开头， UrlBasedViewResolver 就会将其解析为请求重定向，后面的视图名就是将重定向的 url。</p>
<p>这样和返回 RedirectView 的效果是一样的，他可以将请求重定向到当前 Servlet 上下文的相对路径，如果写成这样 <code>redirect:http://myhost.com/some/arbitrary/path</code>，就会重定向到这个绝对路径上。</p>
<p>如果在控制器的方法上写了 @ResponseStatus 注解，则注解中的状态码优先权高于 RedirectView 中的。</p>
<h2 id="转发"><a href="#转发" class="headerlink" title="转发"></a>转发</h2><p>如果最终的视图解析器为 UrlBasedViewResolver， 则可以使用 <code>forward:</code>，效果通过 forward() 方法创建一个 InternalResourceView 。这个前缀不适用于 InternalResourceViewResolver 和 InternalResourceView （JSP），但对于使用其他的视图技术且想执行请求转发，就非常有用了。同样，将多个视图解析器组成处理链实现链式处理。</p>
<h2 id="内容规约"><a href="#内容规约" class="headerlink" title="内容规约"></a>内容规约</h2><p>ContentNegotiatingViewResolver 实际并不会解析视图，而是调用其他视图解析器，查找与客户端请求中有关信息匹配的视图。这些信息可以从请求头中的 <code>Accept</code> 中或 url 中参数获得。</p>
<p>ContentNegotiatingViewResolver 将请求的媒体类型与 ViewResolvers 关联的 View 支持的媒体类型（也称为 Content-Type）进行比较，选择最佳的 View 来处理请求。 与这个 Content-Type 相符的第一个视图会被首先返回给客户端。 如果 ViewResolver 链无法解析视图，则会在 DefaultViews 的视图列表进行查找。 后者适用于无需进行业务逻辑处理的单例 View ，因此不用考虑逻辑视图名。 Accept 头中可以包含通配符，例如 <code>text/ *</code> ，则将匹配 content-type 为 <code>text/xml</code>的 View 。</p>
<h1 id="9-语言环境"><a href="#9-语言环境" class="headerlink" title="9. 语言环境"></a>9. 语言环境</h1><p>Spring MVC 和 Spring 中的大多数模块一样，也提供了内容国际化的功能。DispatcherServlet 可以根据客户端的语言环境进行内容的自动国际化，这要归功于 LocaleResolver。</p>
<p>DispatcherServlet 接受到请求后会去上下文中查找 LocaleResolver bean，找到后就会使用它完成国际化的任务。可以调用 RequestContext.getLocale() 来获得请求的语言环境。</p>
<p>如果不想使用默认的自动解析方式，还可以通过在处理程序映射中添加一个拦截器来实现，比如解析 url 中的参数。</p>
<p>有关国际化的解析器和拦截器都定义在 <code>org.springframework.web.servlet.i18n</code> 中，并且都需要在应用上下文中配置。Spring 可以国际化这些内容：</p>
<h2 id="时区"><a href="#时区" class="headerlink" title="时区"></a>时区</h2><p>除了语言环境，有时还需要获得客户端的时区信息，LocaleContextResolver 对 LocaleResolver 中的功能进行了扩展，这样可以在 LocaleContext 中获得更为丰富的信息。</p>
<p>通过 RequestContext.getTimeZone()方法获取客户端的时区信息，在 Spring 的 ConversionService 中注册的日期/时间转换器和格式化器会自动获取这些信息。</p>
<h2 id="请求头"><a href="#请求头" class="headerlink" title="请求头"></a>请求头</h2><p>这个区域解析器会识别请求中的 <code>accept-language</code> 头，这个字段一般包含客户操作系统的区域信息，但是它无法获得客户端的时区信息。</p>
<h2 id="Cookie"><a href="#Cookie" class="headerlink" title="Cookie"></a>Cookie</h2><p>这个区域解析器会检查客户端上的 Cookie 是否存在语言或时区信息。这个区域解析器可以设置 cookie 的名字和失效时间。在 xml 文件中定义 CookieLocaleResolver：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"localeResolver"</span> <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.i18n.CookieLocaleResolver"</span>&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 根据具体情况自定义 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"cookieName"</span> <span class="attr">value</span>=<span class="string">"clientlanguage"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">&lt;!-- 100000 为秒数，值为 -1 时, cookie 会在浏览器关闭时被销毁 --&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"cookieMaxAge"</span> <span class="attr">value</span>=<span class="string">"100000"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p><em>CookieLocaleResolver 部分属性的含义</em></p>
<table>
<thead>
<tr>
<th>属性</th>
<th>默认值</th>
<th>含义</th>
</tr>
</thead>
<tbody>
<tr>
<td> cookieName</td>
<td>类名+语言环境</td>
<td>cookie 的名称</td>
</tr>
<tr>
<td> cookieMaxAge</td>
<td>Servlet 容器中规定的值</td>
<td>cookie 的有效期，值为 -1 时, cookie 会在浏览器关闭时被销毁</td>
</tr>
<tr>
<td> cookiePath</td>
<td>/</td>
<td>将 cookie 的作用域限制到制定的相对路径下，cookie 将只在这个路径及其自路径中有效</td>
</tr>
</tbody>
</table>
<h2 id="Session"><a href="#Session" class="headerlink" title="Session"></a>Session</h2><p>SessionLocaleResolver 可以从会话上下文中获取语言和时区信息，它和 CookieLocaleResolver 的区别是：它是在 Servlet 容器的 session 中存储语言和时区信息，所有，这些信息都是暂时的，会话结束后也就不复存在了。</p>
<h2 id="语言环境拦截器"><a href="#语言环境拦截器" class="headerlink" title="语言环境拦截器"></a>语言环境拦截器</h2><p>LocaleChangeInterceptor bean 可以通过自定义配置来修改请求中的参数，达到修改语言环境的目的。调用 LocaleResolver 中的 setLocal() 方法即可。下面的例子演示将所有请求中的 siteLanguage 参数修改为荷兰语：</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"localeChangeInterceptor"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.i18n.LocaleChangeInterceptor"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"paramName"</span> <span class="attr">value</span>=<span class="string">"siteLanguage"</span>/&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"localeResolver"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.i18n.CookieLocaleResolver"</span>/&gt;</span></span><br><span class="line"></span><br><span class="line"><span class="tag">&lt;<span class="name">bean</span> <span class="attr">id</span>=<span class="string">"urlMapping"</span></span></span><br><span class="line"><span class="tag">        <span class="attr">class</span>=<span class="string">"org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"interceptors"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">list</span>&gt;</span></span><br><span class="line">            <span class="tag">&lt;<span class="name">ref</span> <span class="attr">bean</span>=<span class="string">"localeChangeInterceptor"</span>/&gt;</span></span><br><span class="line">        <span class="tag">&lt;/<span class="name">list</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">property</span> <span class="attr">name</span>=<span class="string">"mappings"</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">value</span>&gt;</span>/**/*.view=someController<span class="tag">&lt;/<span class="name">value</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">property</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">bean</span>&gt;</span></span><br></pre></td></tr></table></figure>
<h1 id="10-主题"><a href="#10-主题" class="headerlink" title="10. 主题"></a>10. 主题</h1><p>Spring Web MVC 框架支持自定义主题，应用程序的整体外观可以实现统一修改。主题即静态资源的集合，通常是 CSS 和图片，两者决定了应用的整体风格。</p>
<h2 id="主题的定义"><a href="#主题的定义" class="headerlink" title="主题的定义"></a>主题的定义</h2><p>必须定义一个 <code>org.springframework.ui.context.ThemeSource</code> 接口的实现类才能使用主题功能。默认情况下，WebApplicationContext 通过 <code>org.springframework.ui.context.support.ResourceBundleThemeSource</code> 实现主题功能，它从 classpath 的根目录读取配置文件。 要使用自定义的 ThemeSource，需要配置 ResourceBundleThemeSource 的主题名称前缀，在应用程序上下文中注册一个 themeSource bean。</p>
<p>使用 ResourceBundleThemeSource 自定义主题，需要将配置写在 properties 文件中，这个文件中包含了构成主题的所有资源。</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">styleSheet=/themes/cool/style.css</span><br><span class="line">background=/themes/cool/img/coolBg.jpg</span><br></pre></td></tr></table></figure>
<p>在 JSP 中使用主题设置，要用到 <code>spring:theme</code> 标签：</p>
<figure class="highlight html"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">%@</span> <span class="attr">taglib</span> <span class="attr">prefix</span>=<span class="string">"spring"</span> <span class="attr">uri</span>=<span class="string">"http://www.springframework.org/tags"</span>%&gt;</span></span><br><span class="line"><span class="tag">&lt;<span class="name">html</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">head</span>&gt;</span></span><br><span class="line">        <span class="tag">&lt;<span class="name">link</span> <span class="attr">rel</span>=<span class="string">"stylesheet"</span> <span class="attr">href</span>=<span class="string">"&lt;spring:theme code='styleSheet'/&gt;"</span> <span class="attr">type</span>=<span class="string">"text/css"</span>/&gt;</span></span><br><span class="line">    <span class="tag">&lt;/<span class="name">head</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">body</span> <span class="attr">style</span>=<span class="string">"background=&lt;spring:theme code='background'/&gt;"</span>&gt;</span></span><br><span class="line">        ...</span><br><span class="line">    <span class="tag">&lt;/<span class="name">body</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">html</span>&gt;</span></span><br></pre></td></tr></table></figure>
<p>默认情况下，ResourceBundleThemeSource 主题名前缀是空的。properties 文件是从 classpath 的根目录读取的。所以应当将 abc.properties 配置文件放到根目录下（<code>/WEB-INF/classes</code>）。 ResourceBundleThemeSource 可以实现主题的国际化。比如，<code>/WEB-INF/classes/abc_nl.properties</code>，结合上面对 background 属性的配置，可以实现将背景切换为带有荷兰文字的背景图片。</p>
<h2 id="主题的解析"><a href="#主题的解析" class="headerlink" title="主题的解析"></a>主题的解析</h2><p>定义好主题配置后，当有请求发来时，在预处理阶段，通过查找上下文中叫 <code>themeResolver</code> 的 bean 来对决定用什么解析器来解析主题，这里的工作原理和上文中的 <code>localeResolver</code> 一样。通过识别带有不同参数的请求来对请求的主题进行切换。Spring 提供了这几种 themeResolver:</p>
<table>
<thead>
<tr>
<th>类名</th>
<th>功能</th>
</tr>
</thead>
<tbody>
<tr>
<td> FixedThemeResolver</td>
<td>通过读取 <code>defaultThemeName</code> 属性来选择固定的主题</td>
</tr>
<tr>
<td> SessionThemeResolver</td>
<td>主题信息由 session 保存，每个 session 只需解析一次，不同的 session 之间无法共享</td>
</tr>
<tr>
<td> FixedThemeResolver</td>
<td>主题信息保存在客户端的 cookie 中</td>
</tr>
</tbody>
</table>
<p>Spring 还提供了一个 <code>ThemeChangeInterceptor</code> 拦截器，通过识别请求的参数来切换主题。</p>
<h1 id="11-Multipart"><a href="#11-Multipart" class="headerlink" title="11. Multipart"></a>11. Multipart</h1><p><code>org.springframework.web.multipart.MultipartResolver</code> 提供了一种处理表单上传文件的解决方案，有两种实现方式，一种是基于 Apache 的 Commons-Fileupload，另一种是基于 Servlet 3.0 的。</p>
<p>首先要在 Spring 的配置文件中为 DispatcherServlet 声明一个叫做 <code>MultipartResolver</code> 的 bean，DispatcherServlet 会自动识别并调用它来处理文件上传请求。它会将 content-type 为 <code>multipart/form-data</code> 的请求包装成 <code>MultipartHttpServletRequest</code>，从而将这些 “part” 暴露为请求的一个参数。</p>
<h2 id="Apache-FileUpload"><a href="#Apache-FileUpload" class="headerlink" title="Apache FileUpload"></a>Apache FileUpload</h2><p>要想使用 Apache Commons-Fileupload，需要将 <code>multipartResolver</code> bean 配置为 <code>CommonsMultipartResolver</code>，另外不要忘了添加 <code>commons-fileupload</code> 的依赖。</p>
<h2 id="Servlet-3-0"><a href="#Servlet-3-0" class="headerlink" title="Servlet 3.0"></a>Servlet 3.0</h2><p>如果通过 Servlet 3.0 处理 multipart 请求，则同样需要在 DispatcherServlet 中注册。在 Java 代码中配置的话，需要添加一个 <code>MultipartConfigElement</code>；在 xml 文件中配置的话，添加 <code>&lt;multipart-config&gt;</code> 节点。文件大小限制和文件保存位置等选项同样需要这样配置，因为在 Servlet 3.0 以后，不允许 <code>MultipartResolver</code> 这么干了。</p>
<p>Servlet 3.0 配置好后，只需要在 xml 文件中将 <code>multipartResolver</code> hean 配置为 <code>StandartMultipartResolver</code> 即可。</p>

      
    </div>
    
    
    

    

    <!-- s reward 默认位置 -->

    <!-- e resume 默认位置 -->
    
      <div>
        <ul class="post-copyright">
  <li class="post-copyright-author">
    <strong>本文作者：</strong>
    郑保乐
  </li>
  <li class="post-copyright-link">
    <strong>本文链接：</strong>
    <a href="https://james.letec.top/2018/03/29/SpringMVC 解析之 DispatcherServlet/" title="SpringMVC 解析之 DispatcherServlet">https://james.letec.top/2018/03/29/SpringMVC 解析之 DispatcherServlet/</a>
  </li>
  <li class="post-copyright-license">
    <strong>版权声明： </strong>
    本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/3.0/" rel="external nofollow" target="_blank">CC BY-NC-SA 3.0</a> 许可协议。转载请注明出处！
  </li>
</ul>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Spring/" rel="tag"># Spring</a>
          
            <a href="/tags/Spring-MVC/" rel="tag"># Spring MVC</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2018/02/24/Python 第一个爬虫-教务系统信息收集/" rel="next" title="Python 第一个爬虫-教务系统信息收集">
                <i class="fa fa-chevron-left"></i> Python 第一个爬虫-教务系统信息收集
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2018/03/29/基于SpringBoot的个人博客/" rel="prev" title="基于 Spring Boot 的个人博客">
                基于 Spring Boot 的个人博客 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style"><span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_qzone"></a>
<a class="jiathis_button_weixin"></a>
<a class="jiathis_button_tsina"></a>
<a class="jiathis_button_tqq"></a>
<a class="jiathis_button_cqq"></a>
<a class="jiathis_button_qq"></a>
<a class="jiathis_button_kaixin001"></a>
<a class="jiathis_button_douban"></a>
<a class="jiathis_button_tieba"></a>
<a class="jiathis_button_renren"></a>
<a class="jiathis_button_ydnote"></a>
<a href="http://www.jiathis.com/share?uid=2160247" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank"></a>
</div>
<script type="text/javascript" >
var jiathis_config={
	data_track_clickback:true,
	summary:"",
	shortUrl:false,
	hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=2160247" charset="utf-8"></script>
<!-- JiaThis Button END -->

      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
        <div id="cyReward" role="cylabs" data-use="reward" style="padding: 10px 0; margin: 0px auto; width: 90%; text-align: center;"></div>
      <div id="SOHUCS"></div>
    </div>

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/images/avatar.jpg"
                alt="郑保乐" />
            
              <p class="site-author-name" itemprop="name">郑保乐</p>
              <p class="site-description motion-element" itemprop="description">优秀的判断力来自经验，<br>但经验来自错误的判断。</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">32</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">7</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">31</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          
            <div class="feed-link motion-element">
              <a href="/atom.xml" rel="alternate">
                <i class="fa fa-rss"></i>
                RSS
              </a>
            </div>
          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/JamesZBL" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="tencent://message/?uin=1146556298&Site=摆码王子" target="_blank" title="QQ">
                      
                        <i class="fa fa-fw fa-qq"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/James1996" target="_blank" title="Weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i></a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="mailto:zhengbaole_1996@163.com" target="_blank" title="E-Mail">
                      
                        <i class="fa fa-fw fa-envelope"></i></a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-inline">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                友情链接
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://www.jianshu.com/u/77df8abd9a98" title="EEE凯飞" target="_blank">EEE凯飞</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://winterchen.com/" title="WinterChen" target="_blank">WinterChen</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://wuchong.me/" title="云邪" target="_blank">云邪</a>
                  </li>
                
                  <li class="links-of-blogroll-item">
                    <a href="http://zmister.com/" title="州的先生" target="_blank">州的先生</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#Spring-MVC-是什么"><span class="nav-number">1.</span> <span class="nav-text">Spring MVC 是什么</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#DispatcherServlet"><span class="nav-number">2.</span> <span class="nav-text">DispatcherServlet</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#1-应用上下文的层次结构"><span class="nav-number">3.</span> <span class="nav-text">1. 应用上下文的层次结构</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#2-带有特殊功能的-Bean"><span class="nav-number">4.</span> <span class="nav-text">2. 带有特殊功能的 Bean</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#3-Web-MVC-的配置"><span class="nav-number">5.</span> <span class="nav-text">3. Web MVC 的配置</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#4-Servlet-的配置"><span class="nav-number">6.</span> <span class="nav-text">4.  Servlet 的配置</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#5-处理请求"><span class="nav-number">7.</span> <span class="nav-text">5. 处理请求</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#6-拦截器"><span class="nav-number">8.</span> <span class="nav-text">6. 拦截器</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#7-异常处理"><span class="nav-number">9.</span> <span class="nav-text">7. 异常处理</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#处理方式"><span class="nav-number">9.1.</span> <span class="nav-text">处理方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Servlet-容器中定义的错误页面-error-page"><span class="nav-number">9.2.</span> <span class="nav-text">Servlet 容器中定义的错误页面 (error-page)</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#8-视图名解析"><span class="nav-number">10.</span> <span class="nav-text">8. 视图名解析</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#处理方式-1"><span class="nav-number">10.1.</span> <span class="nav-text">处理方式</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#重定向"><span class="nav-number">10.2.</span> <span class="nav-text">重定向</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#转发"><span class="nav-number">10.3.</span> <span class="nav-text">转发</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#内容规约"><span class="nav-number">10.4.</span> <span class="nav-text">内容规约</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#9-语言环境"><span class="nav-number">11.</span> <span class="nav-text">9. 语言环境</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#时区"><span class="nav-number">11.1.</span> <span class="nav-text">时区</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#请求头"><span class="nav-number">11.2.</span> <span class="nav-text">请求头</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Cookie"><span class="nav-number">11.3.</span> <span class="nav-text">Cookie</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Session"><span class="nav-number">11.4.</span> <span class="nav-text">Session</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#语言环境拦截器"><span class="nav-number">11.5.</span> <span class="nav-text">语言环境拦截器</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#10-主题"><span class="nav-number">12.</span> <span class="nav-text">10. 主题</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#主题的定义"><span class="nav-number">12.1.</span> <span class="nav-text">主题的定义</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#主题的解析"><span class="nav-number">12.2.</span> <span class="nav-text">主题的解析</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#11-Multipart"><span class="nav-number">13.</span> <span class="nav-text">11. Multipart</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#Apache-FileUpload"><span class="nav-number">13.1.</span> <span class="nav-text">Apache FileUpload</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Servlet-3-0"><span class="nav-number">13.2.</span> <span class="nav-text">Servlet 3.0</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; 2015 &mdash; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">郑保乐 | James Zheng</span>

  
    <span class="post-meta-divider">|</span>
    <span class="post-meta-item-icon">
      <i class="fa fa-area-chart"></i>
    </span>
    
      <span class="post-meta-item-text">一共写了&#58;</span>
    
    <span title="一共写了">43.5k字</span>
  
</div>


  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







  <div>
    <div style="display:inline-block; vertical-align: middle;">
        <script type="text/javascript">var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan id='cnzz_stat_icon_1273289170'%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1273289170%26show%3Dpic' type='text/javascript'%3E%3C/script%3E"));</script>
    </div>

    
    <span class="post-meta-divider"></span>
    <div style="display:inline-block;">
    <a href="http://www.miitbeian.gov.cn/">冀ICP备18000182号</a>
    </div>
    
    <span class="post-meta-divider"></span>
    <div style="display:inline-block;">
        <img src="/images/beian.png" style="display: inline-block;vertical-align:middle;margin:0px,5px,5px,0px;"/>
        <a target="_blank" href="http://www.beian.gov.cn/portal/registerSystemInfo?recordcode=13010802000830">冀公网安备 13010802000830号</a>
    </div>
  </div>



        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery/2.1.3/jquery.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fastclick/1.0.6/fastclick.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/jquery.lazyload/1.9.3/jquery.lazyload.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/velocity/1.2.3/velocity.ui.min.js"></script>
  

  
  
    <script type="text/javascript" src="//cdn.jsdelivr.net/fancybox/2.1.5/jquery.fancybox.pack.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  




  

    <script type="text/javascript">
    (function(){
      var appid = 'cytxDP7hE';
      var conf = 'e4d56467e3e0e8e707d560e87196ea24';
      var width = window.innerWidth || document.documentElement.clientWidth;
      if (width < 960) {
      window.document.write('<script id="changyan_mobile_js" charset="utf-8" type="text/javascript" src="https://changyan.sohu.com/upload/mobile/wap-js/changyan_mobile.js?client_id=' + appid + '&conf=' + conf + '"><\/script>'); } else { var loadJs=function(d,a){var c=document.getElementsByTagName("head")[0]||document.head||document.documentElement;var b=document.createElement("script");b.setAttribute("type","text/javascript");b.setAttribute("charset","UTF-8");b.setAttribute("src",d);if(typeof a==="function"){if(window.attachEvent){b.onreadystatechange=function(){var e=b.readyState;if(e==="loaded"||e==="complete"){b.onreadystatechange=null;a()}}}else{b.onload=a}}c.appendChild(b)};loadJs("https://changyan.sohu.com/upload/changyan.js",function(){
        window.changyan.api.config({appid:appid,conf:conf})});
      }
    })();
    </script>
    <script type="text/javascript" src="https://assets.changyan.sohu.com/upload/plugins/plugins.count.js"></script>

    <script type="text/javascript" charset="utf-8" src="https://changyan.itc.cn/js/lib/jquery.js"></script>
    <script type="text/javascript" charset="utf-8" src="https://changyan.sohu.com/js/changyan.labs.https.js?appid=cytxDP7hE"></script>
  









  




  
  
  
  <link rel="stylesheet" href="/lib/algolia-instant-search/instantsearch.min.css">

  
  
  <script src="/lib/algolia-instant-search/instantsearch.min.js"></script>
  

  <script src="/js/src/algolia-search.js?v=5.1.4"></script>



  

  
  <script src="https://cdn1.lncld.net/static/js/av-core-mini-0.6.4.js"></script>
  <script>AV.initialize("noQxgNi7RfBVPLkKkLSqJfgu-gzGzoHsz", "KgdngJPIsywPsYCvOUx1zF88");</script>
  <script>
    function showTime(Counter) {
      var query = new AV.Query(Counter);
      var entries = [];
      var $visitors = $(".leancloud_visitors");

      $visitors.each(function () {
        entries.push( $(this).attr("id").trim() );
      });

      query.containedIn('url', entries);
      query.find()
        .done(function (results) {
          var COUNT_CONTAINER_REF = '.leancloud-visitors-count';

          if (results.length === 0) {
            $visitors.find(COUNT_CONTAINER_REF).text(0);
            return;
          }

          for (var i = 0; i < results.length; i++) {
            var item = results[i];
            var url = item.get('url');
            var time = item.get('time');
            var element = document.getElementById(url);

            $(element).find(COUNT_CONTAINER_REF).text(time);
          }
          for(var i = 0; i < entries.length; i++) {
            var url = entries[i];
            var element = document.getElementById(url);
            var countSpan = $(element).find(COUNT_CONTAINER_REF);
            if( countSpan.text() == '') {
              countSpan.text(0);
            }
          }
        })
        .fail(function (object, error) {
          console.log("Error: " + error.code + " " + error.message);
        });
    }

    function addCount(Counter) {
      var $visitors = $(".leancloud_visitors");
      var url = $visitors.attr('id').trim();
      var title = $visitors.attr('data-flag-title').trim();
      var query = new AV.Query(Counter);

      query.equalTo("url", url);
      query.find({
        success: function(results) {
          if (results.length > 0) {
            var counter = results[0];
            counter.fetchWhenSave(true);
            counter.increment("time");
            counter.save(null, {
              success: function(counter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(counter.get('time'));
              },
              error: function(counter, error) {
                console.log('Failed to save Visitor num, with error message: ' + error.message);
              }
            });
          } else {
            var newcounter = new Counter();
            /* Set ACL */
            var acl = new AV.ACL();
            acl.setPublicReadAccess(true);
            acl.setPublicWriteAccess(true);
            newcounter.setACL(acl);
            /* End Set ACL */
            newcounter.set("title", title);
            newcounter.set("url", url);
            newcounter.set("time", 1);
            newcounter.save(null, {
              success: function(newcounter) {
                var $element = $(document.getElementById(url));
                $element.find('.leancloud-visitors-count').text(newcounter.get('time'));
              },
              error: function(newcounter, error) {
                console.log('Failed to create');
              }
            });
          }
        },
        error: function(error) {
          console.log('Error:' + error.code + " " + error.message);
        }
      });
    }

    $(function() {
      var Counter = AV.Object.extend("Counter");
      if ($('.leancloud_visitors').length == 1) {
        addCount(Counter);
      } else if ($('.post-title-link').length > 1) {
        showTime(Counter);
      }
    });
  </script>



  

  
<script>
(function(){
    var bp = document.createElement('script');
    var curProtocol = window.location.protocol.split(':')[0];
    if (curProtocol === 'https') {
        bp.src = 'https://zz.bdstatic.com/linksubmit/push.js';        
    }
    else {
        bp.src = 'http://push.zhanzhang.baidu.com/push.js';
    }
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(bp, s);
})();
</script>


  
  

  

  

  

</body>
</html>
